package com.cnbot.dchttpsdk.interceptor;

import android.text.TextUtils;

import com.cnbot.dchttpsdk.download.DownloadProgressResponseBody;
import com.cnbot.dchttpsdk.helper.DownFileProgressListener;

import java.io.File;
import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Copyright (c) 2016-a  Hunan Cnbot Co., Ltd. All Rights Reserved.
 *
 * @descriptoin 下载文件拦截器
 * @FileName: DownloadProgressInterceptor.java
 * @author: dc
 * @date: 2019/1/19 14:10
 * @version: 1.0
 */

public class DownloadProgressInterceptor implements Interceptor {
    private long startPos;
    private DownFileProgressListener listener;

    public DownloadProgressInterceptor(DownFileProgressListener listener, File file) {
        this.listener = listener;
        startPos = readFile(file);
    }

    public DownloadProgressInterceptor(DownFileProgressListener listener, String path) {
        this.listener = listener;
        startPos = readFile(path);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        //断点续传
        Request request = chain.request().newBuilder().addHeader("Range", "bytes=" + startPos + "-").build();
        Response originalResponse = chain.proceed(request);
        return originalResponse.newBuilder().body(new DownloadProgressResponseBody(originalResponse.body(), listener)).build();
    }

    /**
     * 读取文件长度
     *
     * @date 2018.8.17   modified by ww
     * 加入file是否为文件的判断
     */
    public long readFile(File file) {
        if (file != null && file.exists() && file.isFile()) {
            return file.length();
        } else {
            return 0;
        }
    }

    /**
     * 读取文件长度
     *	@date 2018.8.17
     *  @author ww
     */
    public long readFile(String path) {
        if (TextUtils.isEmpty(path)) {
            return 0;
        }
        File file = new File(path);
        return readFile(file);
    }
}